package test.demo.support;

import test.demo.BeansException;
import test.demo.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Description:
 * @author: JC
 * @date: 2023/4/5 12:41
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy{
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        try {
            Class beanClass = beanDefinition.getBeanClass();
            if(ctor != null){
                return beanClass.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            }else{
                return beanClass.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException | NoSuchMethodException | IllegalAccessException |
                InvocationTargetException e) {
            throw new BeansException(e.getCause().toString());
        }
    }
}
